import React, { useEffect, useState } from "react";
import {
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PieChartOutlined,
} from "@ant-design/icons";
import { Link, useLocation } from "react-router-dom";
import { Breadcrumb, Flex, Tabs } from "antd";

import Routers from "./router/router";
import type { MenuProps } from "antd";
import { Button, Menu } from "antd";
import { useNavigate } from "react-router-dom";
import { loading } from "./common/GlobalLoading";
import { message } from "antd";
import { LogoutOutlined } from "@ant-design/icons";

type MenuItem = Required<MenuProps>["items"][number];

const items: MenuItem[] = [
  {
    key: "system",
    label: "系统管理",
    icon: <MailOutlined />,
    children: [{ key: "11", label: <Link to="/router">路由管理</Link> }],
  },
  {
    key: "alarm",
    label: "报警管理",
    icon: <MailOutlined />,
    children: [{ key: "12", label: <Link to="/alarm">故障列表</Link> }],
  },
  {
    key: "devices",
    label: "设备接入",
    icon: <MailOutlined />,
    children: [
      { key: "5", label: <Link to="/project">项目管理</Link> },
      { key: "6", label: <Link to="/deviceGroup">分组管理</Link> },
      { key: "device", label: <Link to="/device">设备管理</Link> },
      { key: "8", label: <Link to="/deviceTemplate">设备模板</Link> },
      { key: "9", label: <Link to="/listMonitor">远程调试</Link> },
      { key: "10", label: <Link to="/protocol">协议管理</Link> },
      {
        key: "registerGroupLists",
        label: <Link to="/registerGroupLists">寄存器分组管理</Link>,
      },
    ],
  },
  {
    key: "crontab",
    label: "任务管理",
    icon: <MailOutlined />,
    children: [{ key: "1", label: <Link to="/crontab">任务列表</Link> }],
  },
];
const routeMap: Record<string, string> = {
  "/": "首页",
  "/login": "登录",
};
items.forEach((item: any) => {
  item.children.forEach((child: any) => {
    routeMap[child.label.props.to] = child.label.props.children;
    routeMap[child.label.props.to + "_parent_text"] = item.label;
  });
});
function DynamicBreadcrumb() {
  const location = useLocation();
  const pathSnippets = location.pathname.split("/").filter((i) => i);

  const breadcrumbItems = [
    <Breadcrumb.Item key="home">
      <Link to="/">首页</Link>
    </Breadcrumb.Item>,
    ...pathSnippets.map((_, index) => {
      const url = `/${pathSnippets.slice(0, index + 1).join("/")}`;
      return (
        <>
          <Breadcrumb.Item key={url}>
            <Link to={url}>{routeMap[url] || "未知页面"}</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item key={url}>
            {routeMap[url + "_parent_text"] || "未知页面"}{" "}
          </Breadcrumb.Item>
        </>
      );
    }),
  ];

  return (
    <Breadcrumb style={{ margin: "16px 0" }}>{breadcrumbItems}</Breadcrumb>
  );
}

const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const [historyRouter, setHistoryRouter] = useState<any>([]);
  // 初始化时直接从localStorage获取用户信息，避免首次渲染为null
  const getUserInfoFromStorage = () => {
    const token = localStorage.getItem("token");
    const userInfoStr = localStorage.getItem("userInfo");

    if (token && userInfoStr) {
      try {
        return JSON.parse(userInfoStr);
      } catch (error) {
        console.error("解析用户信息失败:", error);
        return null;
      }
    }
    return null;
  };

  const [userInfo, setUserInfo] = useState<any>(getUserInfoFromStorage());

  // 检查登录状态和路由重定向
  useEffect(() => {
    const checkLoginStatus = () => {
      // 如果用户未登录且不是在登录页面，则重定向到登录页
      if (!userInfo && location.pathname !== "/login") {
        navigate("/login");
      }
    };

    checkLoginStatus();
  }, [userInfo, location.pathname, navigate]);

  // 如果是登录页面或者未登录，直接渲染路由内容
  if (userInfo == null || location.pathname === "/login") {
    return <Routers />;
  }

  useEffect(() => {
    // 避免重复添加相同的路由记录
    if (!historyRouter.some((item: any) => item.key === location.pathname)) {
      setHistoryRouter((prev: any) => [
        ...prev,
        {
          label: routeMap[location.pathname] || "未知页面",
          key: location.pathname,
          action: "PUSH", // 改为PUSH更准确
          timestamp: new Date().toISOString(),
        },
      ]);
    }
  }, [location, historyRouter]); // 添加historyRouter作为依赖
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  // 退出登录
  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("userId");
    localStorage.removeItem("userInfo");
    setUserInfo(null);
    message.success('退出登录成功');
    // navigate('/login');
    window.location.href = '/login';
  };

  // 已登录状态，显示完整布局
  return (
    <div id="app" style={{ display: "flex", height: "100vh" }}>
      <div
        className={collapsed ? "main_menu_min" : "main_menu"}
        style={{ width: collapsed ? 80 : 200 }}
      >
        <Button
          className="change_menu"
          type="primary"
          size="small"
          onClick={toggleCollapsed}
          style={{ marginBottom: 16 }}
        >
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </Button>
        <Flex justify="left" align="center">
          <img
            src="/public/assets/image/logo.png"
            alt="Logo"
            style={{ width: "160px" }}
          />
        </Flex>
        <Menu
          defaultSelectedKeys={["1"]}
          defaultOpenKeys={["sub1"]}
          mode="inline"
          theme="dark"
          inlineCollapsed={collapsed}
          items={items}
        />
      </div>
      <div
        className="app_main"
        style={{ flex: 1, overflow: "auto", padding: 16 }}
      >
        {/* 显示用户信息和退出登录按钮 */}
        {userInfo && (
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              marginBottom: "16px",
            }}
          >
            <span>欢迎，{userInfo.realName}</span>
            <Button
              type="text"
              icon={<LogoutOutlined />}
              onClick={handleLogout}
              style={{ color: "#e74c3c" }}
            >
              退出登录
            </Button>
          </div>
        )}

        <Tabs
          type="editable-card"
          items={historyRouter}
          onEdit={(targetKey, action) => {
            if (action === "remove" && typeof targetKey === "string") {
              const newHistoryRouter = historyRouter.filter(
                (item: any) => item.key !== targetKey
              );
              setHistoryRouter(newHistoryRouter);

              if (
                targetKey === location.pathname &&
                newHistoryRouter.length > 0
              ) {
                navigate(newHistoryRouter[0].key);
              }

              if (newHistoryRouter.length === 0) {
                navigate("/");
              }
            }
          }}
          hideAdd
          onChange={(key) => navigate(key)}
        />
        <DynamicBreadcrumb />
        <Routers />
      </div>
    </div>
  );
};

export default App;
